package com.elysia.visionmanagerspringboot.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.elysia.visionmanagerspringboot.domain.dto.PhotoDTO;
import com.elysia.visionmanagerspringboot.domain.entity.Photo;
import com.elysia.visionmanagerspringboot.domain.vo.PhotoVO;
import com.elysia.visionmanagerspringboot.enumeration.ResourceTypeEnum;
import com.elysia.visionmanagerspringboot.mapper.PhotoMapper;
import com.elysia.visionmanagerspringboot.result.Result;
import com.elysia.visionmanagerspringboot.service.IPhotoService;
import com.elysia.visionmanagerspringboot.untils.AliyunOssUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RequiredArgsConstructor
@Service
@Slf4j
public class IPhotoServiceImpl extends ServiceImpl<PhotoMapper, Photo> implements IPhotoService {
    private final AliyunOssUtil aliyunOssUtil;
    @Override
    public Result<Object> update(PhotoDTO photoDTO) throws IOException {
        String fileKey = aliyunOssUtil.uploadFile(photoDTO.getFile(), ResourceTypeEnum.PHOTO);
        Photo photo = Photo.builder()
                .fileKey(fileKey)
                .alt(photoDTO.getAlt())
                .caption(photoDTO.getCaption())
                .build();
        save(photo);
        return Result.success();
    }

    @Override
    public Result<Object> getList() {
        List<Photo> list = list();
        List<PhotoVO> result = new ArrayList<>();
        for (Photo photo : list) {
            PhotoVO photoVO = PhotoVO.builder()
                    .id(photo.getId())
                    .url(aliyunOssUtil.getFileUrl(photo.getFileKey(), 3600))
                    .alt(photo.getAlt())
                    .caption(photo.getCaption())
                    .build();
            result.add(photoVO);
        }
        return Result.success(result);
    }

    @Override
    public Result<Object> delete(Long id) {
        Photo photo = getById(id);
        aliyunOssUtil.deleteFile(photo.getFileKey());
        removeById(id);
        return Result.success();
    }
}
